package com.zq.it.service.impl.exam;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

import com.zq.it.dao.common.PageConfig;
import com.zq.it.pojo.Student;
import com.zq.it.pojo.TClass;
import com.zq.it.pojo.Teacher;
import com.zq.it.pojo.exam.TClassTask;
import com.zq.it.pojo.exam.TStudentTask;
import com.zq.it.pojo.exam.TTask;
import com.zq.it.pojo.exam.TTaskmodel;
import com.zq.it.pojo.exam.data.ObjectData;
import com.zq.it.pojo.exam.data.StuTaskData;
import com.zq.it.service.common.BaseServiceImpl;
import com.zq.it.service.exam.TaskService;
import com.zq.it.tool.Constant;
import com.zq.it.tool.StringUtil;

public class TaskServiceImpl extends BaseServiceImpl implements TaskService {

	@Override
	public void addTaskModel(TTaskmodel taskModel) {
		taskmodelDAO.save(taskModel);
	}

	@Override
	public String deleteTaskModel(Long[] ids, String path, Teacher teacher) {
		int num = 0;
		for (long id : ids) {
			TTaskmodel model = taskmodelDAO.findById(id);
			if (model.getUploader() == teacher.getId()) {
				List list = taskDAO.findByHql("from TTask as model where model.TTaskmodel.id =" + id);
				if (null != list && list.size() > 0) {
					num++;
				} else {
					deleteFile(path + "/" + model.getModelUrl());
					deleteFile(path + "/" + model.getDemoteModelUrl());
					deleteFile(path + "/" + model.getAnwserModelUrl());
					taskmodelDAO.delete(model);
				}
			} else {
				throw new RuntimeException("权限不足！");
			}
		}
		if (ids.length > 1 && num > 0) {
			return "more";
		} else if (ids.length == 1 && num == 1) {
			return "one";
		} else {
			return "ok";
		}
	}

	@Override
	public void deleteFile(String path) {
		File temp = new File(path);
		if (temp.isFile()) {
			temp.delete();
		}
	}

	@Override
	public String creatModelHql(TTaskmodel taskModel, String startTime, String endTime, Teacher teacher) {
		StringBuffer hql = new StringBuffer("from TTaskmodel as model where 1=1");
		String modelNameHql = null == taskModel.getModelName()
				|| "".equals(taskModel.getModelName())
						? ""
						: " and model.modelName like '%"
								+ taskModel.getModelName() + "%'";
		String TechHql = null == taskModel.getTechStyle()
				|| "".equals(taskModel.getTechStyle())
						? ""
						: " and model.techStyle like '%"
								+ taskModel.getTechStyle() + "%'";
		String startTimeHql = null == startTime || "".equals(startTime)
				? ""
				: " and model.uploadTime >= '" + startTime + "'";
		String endTimeHql = null == endTime || "".equals(endTime)
				? ""
				: " and model.uploadTime <= '" + endTime + "'";
		String teacherHql = " and model.uploader =" + teacher.getId();
		hql.append(modelNameHql).append(TechHql).append(startTimeHql)
				.append(endTimeHql).append(teacherHql);
		return hql.toString();
	}

	@Override
	public TTaskmodel getTaskModel(Teacher teacher, Long id) {
		String hql = "from TTaskmodel as model where model.uploader=" + teacher.getId() + " and model.id=" + id;
		List list = taskmodelDAO.findByHql(hql);
		if (null != list && list.size() == 1) {
			return (TTaskmodel) list.get(0);
		} else {
			return null;
		}
	}

	@Override
	public void addTask(TTask task) {
		task.setCreateTime(new Timestamp(new Date().getTime()));
		task.setTaskUserCount(0);
		taskDAO.save(task);
	}

	@Override
	public TTask getTaskById(Teacher teacher, Long id) {
		List list = taskDAO.findByHql("from TTask as model where model.teacher.id=" + teacher.getId() + " and model.id=" + id);
		if (null != list && list.size() == 1) {
			return (TTask) list.get(0);
		} else {
			return null;
		}
	}

	@Override
	public ObjectData getTaskModelByTeacher(Teacher teacher) {
		ObjectData data = new ObjectData();
		data.setList(taskmodelDAO.findByUploader(teacher.getId()));
		return data;
	}

	@Override
	public String deleteTask(Teacher teacher, Long[] ids) {
		TTask task;
		int num = 0;
		for (long id : ids) {
			task = taskDAO.findById(id);
			if (task.getTeacher().getId() == teacher.getId()) {
				List list = studentTaskDAO.findByHql(
						"from TStudentTask as model where model.TTask.id ="
								+ id);
				List list2 = classTaskDAO.findByHql(
						"from TClassTask as model where model.TTask.id=" + id);
				if ((null != list && list.size() > 0)
						|| (null != list2 && list2.size() > 0)) {
					num++;
				} else {
					taskDAO.delete(task);
				}
			}
		}
		if (ids.length > 1 && num > 0) {
			return "more";
		} else if (ids.length == 1 && num == 1) {
			return "one";
		} else {
			return "ok";
		}
	}

	@Override
	public String creatTaskHql(TTask task, String startTime, String endTime, Teacher teacher) {
		StringBuffer hql = new StringBuffer("from TTask as model where 1=1");
		String taskNameHql = null == task.getTaskName()
				|| "".equals(task.getTaskName())
						? ""
						: " and model.taskName like '%" + task.getTaskName()
								+ "%'";
		String typeHql = null != task.getCaseType() && task.getCaseType() >= 0
				? " and model.caseType = " + task.getCaseType()
				: "";
		String startTimeHql = null == startTime || "".equals(startTime)
				? ""
				: " and model.createTime >= '" + startTime + "'";
		String endTimeHql = null == endTime || "".equals(endTime)
				? ""
				: " and model.createTime <= '" + endTime + "'";
		String teacherHql = " and model.teacher.id=" + teacher.getId();
		hql.append(taskNameHql).append(typeHql).append(startTimeHql)
				.append(endTimeHql).append(teacherHql);
		return hql.toString();
	}

	@Override
	public void addClassAssign(int[] ids, long taskId, Teacher teacher) {
		TTask task = taskDAO.findById(taskId);
		if (task.getTeacher().getId() == teacher.getId()) {
			for (int id : ids) {
				TClass tclass = getClassDao().findById(id);
				String dir = makeDir(Constant.CLASS_TASK, task.getTaskName() + "/" + tclass.getClassId());
				try {
					List<Student> studentList = getStudentDao().findByClassId(id);
					TClassTask classTask = new TClassTask(getClassDao().findById(id), task, dir);
					classTaskDAO.save(classTask);
					for (Student student : studentList) {
						studentTaskDAO.save(new TStudentTask(student, task, classTask, 0, 0));
					}
					task.setTaskUserCount(task.getTaskUserCount() + 1);
					taskDAO.update(task);
					tclass.setIshaveTask(1);
					getClassDao().update(tclass);
				} catch (Exception e) {
					File file = new File(dir);
					if (file.isDirectory()) {
						deleteDir(file);
					}
				}
			}
		} else {
			throw new RuntimeException("作死的节奏！");
		}
	}

	private String makeDir(String path, String dirName) {
		File dir = new File(path + dirName);
		if (dir.isDirectory()) {
			dirName = dirName + "(" + 1 + ")";
		} else {
			dir.mkdirs();
			return dirName;
		}
		for (int i = 2;; i++) {
			dir = new File(path + dirName);
			if (dir.isDirectory()) {
				dirName = dirName.substring(0, dirName.lastIndexOf("(")) + "("
						+ i + ")";
			} else {
				dir.mkdirs();
				break;
			}
		}
		return dirName;
	}

	@Override
	public ObjectData getStuTaskList(PageConfig config) {
		ObjectData data = getListByPage(config);
		List<TStudentTask> list = data.getList();
		List<StuTaskData> list2 = new ArrayList<StuTaskData>();
		if (null != list) {
			TStudentTask stuTask = null;
			for (int i = 0; i < list.size(); i++) {
				stuTask = list.get(i);
				Student student = getStudentDao().findById(stuTask.getStudent().getId());
				stuTask.setStudent(student);
				TTask task = taskDAO.findById(stuTask.getTTask().getId());
				stuTask.setTTask(task);
				student.setTclass(getClassDao().findById(student.getTclass().getClassId()));
				list2.add(new StuTaskData(stuTask, student.getTclass()));
			}
			data.setList(list2);
		}
		return data;
	}

	@Override
	public String createHavaTaskHql(TStudentTask stuTask, Teacher teacher) {
		StringBuffer hql = new StringBuffer("from TStudentTask as model where 1=1");
		String studentNameHql = null == stuTask.getStudent()
				|| StringUtil.isEmpty(stuTask.getStudent().getStuName()) 
						? ""
						: " and model.student.stuName like '%"+ stuTask.getStudent().getStuName() + "%'";
		String studentNoHql = null == stuTask.getStudent()
				|| null == stuTask.getStudent().getStuId()
						? "" : " and model.student.stuId like '%"
								+ stuTask.getStudent().getStuId() + "%'";
		String taskNameHql = null == stuTask.getTTask()
				|| StringUtil.isEmpty(stuTask.getTTask().getTaskName())
						? ""
						: " and model.TTask.taskName like '%" + stuTask.getTTask().getTaskName() + "%'";
		String typeHql = null != stuTask.getTTask() && stuTask.getTTask().getCaseType() >= 0
						? " and model.TTask.caseType = "
								+ stuTask.getTTask().getCaseType()
						: "";
		String teacherHql = " and model.TTask.teacher.id=" + teacher.getId();
		hql.append(studentNameHql).append(studentNoHql).append(taskNameHql).append(typeHql).append(teacherHql);
		return hql.toString();
	}

	@Override
	public TStudentTask getStuTaskById(Long id, Teacher teacher) {
		TStudentTask stuTask = studentTaskDAO.findById(id);
		stuTask.setTTask(taskDAO.findById(stuTask.getTTask().getId()));
		if (stuTask.getTTask().getTeacher().getId() == teacher.getId()) {
			stuTask.setStudent(getStudentDao().findById(stuTask.getStudent().getId()));
			if (null != stuTask.getTClassTask()) {
				stuTask.setTClassTask(classTaskDAO.findById(stuTask.getTClassTask().getId()));
			}
			return stuTask;
		} else {
			return null;
		}
	}

	@Override
	public void deleteStuTask(Teacher teacher, Long[] ids) {
		int num = 0;
		TStudentTask stuTask;
		for (long id : ids) {
			stuTask = getStuTaskById(id, teacher);
			if (stuTask.getTTask().getTeacher().getId() == teacher.getId()) {
				String dir = null;
				if (stuTask.getTTask().getCaseType() == 0) {
					dir = Constant.STUDENT_TASK;
					if (null != stuTask.getTaskFile() && !"".equals(stuTask.getTaskFile())) {
						deleteFile(dir + stuTask.getTaskFile());
					}
				} else if (stuTask.getTTask().getCaseType() == 1) { // 班级任务
					dir = Constant.CLASS_TASK + stuTask.getTClassTask().getDir();
					if (null != stuTask.getTaskFile()
							&& !"".equals(stuTask.getTaskFile())) {
						deleteFile(dir + stuTask.getTaskFile());
					}
				}
				studentTaskDAO.delete(stuTask);
			}
		}
	}

	@Override
	public void addStudentAssign(Long[] ids, long taskId, Teacher teacher) {
		Student student = null;
		File taskDir = null;
		for (long id : ids) {
			TTask task = taskDAO.findById(taskId);
			if (task.getTeacher().getId() == teacher.getId()) {
				student = getStudentDao().findById(id);
				taskDir = new File(Constant.STUDENT_TASK + task.getTaskName() + "/" + student.getStuId());
				if (!taskDir.isDirectory()) {
					taskDir.mkdirs();
				}
				studentTaskDAO.save(new TStudentTask(student, task, 0, 0));
			} else {
				throw new RuntimeException("作死！");
			}
			task.setTaskUserCount(task.getTaskUserCount() + 1);
			taskDAO.update(task);
		}
	}

	@Override
	public ObjectData getClassTaskListByPage(PageConfig config) {
		ObjectData data = getListByPage(config);
		List<TClassTask> list = data.getList();
		if (null != list) {
			TClassTask classTask = null;
			for (int i = 0; i < list.size(); i++) {
				classTask = list.get(i);
				classTask.setTTask(
						taskDAO.findById(classTask.getTTask().getId()));
				classTask.setTClass(getClassDao()
						.findById(classTask.getTClass().getClassId()));
			}
			data.setList(list);
		}
		return data;
	}

	@Override
	public String createClassTaskHql(TClass tclass, TTask task,
			Teacher teacher) {
		StringBuffer hql = new StringBuffer(
				"from TClassTask as model where 1=1");
		String classNameHql = null == tclass.getClassName()
				|| "".equals(tclass.getClassName())
						? ""
						: " and model.TClass.className like '%"
								+ tclass.getClassName() + "%'";
		String taskNameHql = null == task.getTaskName()
				|| "".equals(task.getTaskName())
						? ""
						: " and model.TTask.taskName like '%"
								+ task.getTaskName() + "%'";
		String teacherHql = " and model.TTask.teacher.id=" + teacher.getId();
		hql.append(classNameHql).append(taskNameHql).append(teacherHql);
		return hql.toString();
	}

	@Override
	public void deleteClassTask(Teacher teacher, Long[] ids) {
		TClassTask classTask;
		for (long id : ids) {
			classTask = classTaskDAO.findById(id);
				deleteDir(new File(Constant.CLASS_TASK + classTask.getDir()));
				classTaskDAO.deleteByHql("delete from TStudentTask as model where model.TClassTask.id =" + id);
				classTaskDAO.delete(classTask);
				List list = classTaskDAO.findByHql("from TClassTask as model where model.TClass.id=" + classTask.getTClass().getClassId());
				if (null == list || list.size() == 0) {
					TClass tclass = getClassDao().findById(classTask.getTClass().getClassId()); //
					tclass.setIshaveTask(0);
					getClassDao().update(tclass);
				}
		}
	}

	@Override
	public String createMyTaskHql(TStudentTask stuTask, Student student) {
		StringBuffer hql = new StringBuffer(
				"from TStudentTask as model where 1=1");
		String taskNameHql = null == stuTask.getTTask().getTaskName()
				|| "".equals(stuTask.getTTask().getTaskName())
						? ""
						: " and model.TTask.taskName like '%"
								+ stuTask.getTTask().getTaskName() + "%'";
		String typeHql = null != stuTask.getTTask().getCaseType()
				&& stuTask.getTTask().getCaseType() >= 0
						? " and model.TTask.caseType = "
								+ stuTask.getTTask().getCaseType()
						: "";
		String demoteHql = null != stuTask.getIsdemote()
				&& stuTask.getIsdemote() >= 0
						? " and model.isdemote = " + stuTask.getIsdemote()
						: "";
		String studentHql = " and model.student.id=" + student.getId();
		hql.append(taskNameHql).append(typeHql).append(demoteHql)
				.append(studentHql);
		return hql.toString();
	}

	@Override
	public TStudentTask getMyTask(Long id, Student student) {
		TStudentTask data = studentTaskDAO.findById(id);
		long stuId = data.getStudent().getId();
		if (stuId != student.getId()) {
			return null;
		} else {
			data.setStudent(getStudentDao().findById(stuId));
			TTask task = taskDAO.findById(data.getTTask().getId());
			task.setTeacher(getTeacherDao().findById(task.getTeacher().getId()));
			task.setTTaskmodel(taskmodelDAO.findById(task.getTTaskmodel().getId()));
			data.setTTask(task);
			if (null != data.getTClassTask()) {
				data.setTClassTask(classTaskDAO.findById(data.getTClassTask().getId()));
			}
			return data;
		}
	}

	@Override
	public boolean updateMyTask(TStudentTask stuTask, Student student) {
		long stuId = stuTask.getStudent().getId();
		if ( stuId == student.getId()) {
			studentTaskDAO.update(stuTask);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void updateStuTask(TStudentTask stuTask) {
		studentTaskDAO.update(stuTask);
	}

	@Override
	public List getStudentTaskList(Long id, Teacher teacher) {
		TClassTask classTask = classTaskDAO.findById(id);
		TTask task = taskDAO.findById(classTask.getTTask().getId());
		if (teacher.getId() == task.getTeacher().getId()) {
			List<TStudentTask> data = studentTaskDAO
					.findByHql("from TStudentTask as t where t.TClassTask.id ="
							+ id + " order by t.student.stuId");
			for (TStudentTask stuTask : data) {
				classTask.setTClass(getClassDao()
						.findById(classTask.getTClass().getClassId()));
				stuTask.setTClassTask(classTask);
				stuTask.setStudent(
						getStudentDao().findById(stuTask.getStudent().getId()));
			}
			return data;
		} else {
			throw new RuntimeException("作死！");
		}
	}

	@Override
	public TClassTask getClassTaskById(Long id, Teacher teacher) {
		TClassTask classTask = classTaskDAO.findById(id);
		classTask.setTClass(
				getClassDao().findById(classTask.getTClass().getClassId()));
		TTask task = taskDAO.findById(classTask.getTTask().getId());
		if (teacher.getId() == task.getTeacher().getId()) {
			return classTask;
		} else {
			throw new RuntimeException("作死！");
		}
	}

	@Override
	public void updateStuScores(TClassTask classTask, Long[] id) {
		List<TStudentTask> data = studentTaskDAO
				.findByHql("from TStudentTask as t where t.TClassTask.id ="
						+ classTask.getId() + " order by t.student.stuId");
		TStudentTask stuTask = null;
		for (int i = 0; i < data.size(); i++) {
			stuTask = data.get(i);
			if (null != id[i]) {
				stuTask.setMark(Integer.parseInt(id[i] + ""));
				studentTaskDAO.update(stuTask);
			}
		}
	}

	@Override
	public HSSFWorkbook getStuScoresWorkbook(TClassTask classTask) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("导出数据");
		HSSFRow row = sheet.createRow(0);
		HSSFCellStyle style = workbook.createCellStyle();
		HSSFFont font = workbook.createFont();
		font.setFontName("黑体");
		style.setFont(font);
		style.setFillBackgroundColor(HSSFColor.YELLOW.index);
		row.setHeight((short) 400);
		String[] head = {"学号", "姓名", "班级", "成绩"};
		for (int i = 0; i < head.length; i++) {
			sheet.setColumnWidth(i, 2500);
			HSSFCell cell = row.createCell(i);
			cell.setCellStyle(style);
			cell.setCellValue(head[i]);
		}
		try {
			List<TStudentTask> data = studentTaskDAO
					.findByHql("from TStudentTask as t where t.TClassTask.id ="
							+ classTask.getId()
							+ " order by t.student.stuId");
			TStudentTask stuTask = null;
			String className = classTask.getTClass().getClassName();
			for (int i = 0; i < data.size(); i++) {
				stuTask = data.get(i);
				stuTask.setStudent(
						getStudentDao().findById(stuTask.getStudent().getId()));
				HSSFRow row_temp = sheet.createRow(i + 1);
				row_temp.createCell(0)
						.setCellValue(stuTask.getStudent().getStuId());
				row_temp.createCell(1)
						.setCellValue(stuTask.getStudent().getStuName());
				row_temp.createCell(2).setCellValue(className);
				row_temp.createCell(3).setCellValue(null == stuTask.getMark()
						? ""
						: stuTask.getMark() + "");
			}
		} catch (Exception e) {
		}
		return workbook;
	}
	
}
